<?php

namespace App\Common\Model\Base\DataUnit\DataOperate;

use App\Common as com;

class JsonOfArray extends com\Cla\ClaBase {

	/**
	 * 字段名
	 * @var string
	 */
	private string $fieldName;

	private ?string $fieldNameOfUnderline = null;

	/**
	 * 数据
	 * @var array
	 */
	private array $data;


	/**
	 * JsonOfArray constructor.
	 * @param string $fieldName 字段名
	 * @param array $data 数据
	 */
	public function __construct( string $fieldName, array $data ) {
		$this->fieldName = $fieldName;
		$this->data = $data;
		parent::__construct();
	}

	public function getFieldName():string {
		return $this->fieldName;
	}

	public function getFieldNameOfUnderline():string {
		if( $this->fieldNameOfUnderline === null ){
			$this->fieldNameOfUnderline = com\Lib\Fun\Str::parseName( $this->fieldName );
		}
		return $this->fieldNameOfUnderline;
	}

	public function getData():array {
		return $this->data;
	}

	/**
	 * 获取数据模型更新数据
	 * @param array $sourceData 源数据（用于检查路径是否存在，如果不存在则创建）
	 * @return array|null
	 */
	public function getModelUpdateData( array $sourceData = [] ):?array {
		if( empty( $this->getData() ) ){
			return null;
		}
		// 给路径目录生成空值，用于存放赋值数据
		$directoryKeyPaths = com\Lib\Fun\Array_::getDirectoryKeyPathOfArray( $this->getData() );
		$directoryKeyPathsOfIndex = [];
		foreach( $directoryKeyPaths as $directoryKeyPathsValue ){
			$keyName = $this->getFieldNameOfUnderline() . "->'$." . str_replace( '->', '.', $directoryKeyPathsValue ) . "'";
			$directoryKeyPathsOfIndex[ $this->getFieldNameOfUnderline() . '->' . $directoryKeyPathsValue ] = \Hyperf\DbConnection\Db::raw( "IF(json_type({$keyName})='OBJECT',$keyName, JSON_OBJECT())" );
		}
		/*		$directoryKeyPathsOfIndex = com\Lib\Fun\Array_::arrayFlip( $directoryKeyPaths, [
					// 'newValue' => \Hyperf\DbConnection\Db::raw( 'JSON_OBJECT()' ),
					'newValue' => \Hyperf\DbConnection\Db::raw( "IF(INVOICE_STATUS=1,2,INVOICE_STATUS)" ),
				] );*/
		// 赋值数据
		return array_merge( $directoryKeyPathsOfIndex, com\Lib\Fun\Array_::toKeyPathArray( [
			$this->getFieldNameOfUnderline() => $this->getData(),
		] ) );
	}




	// ===============================
	//
	//
	// 下面为静态方法
	//
	//
	// ===============================

	/**
	 * @param string $fieldName 字段名
	 * @param array $data 数据
	 * @return $this
	 */
	public static function makeOfNew( string $fieldName, array $data ):self {
		return self::make( $fieldName, $data );
	}


}
